package org.example.ams.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.ams.dao.system.ISysUserDao;
import org.example.ams.entity.system.SysUser;
import org.example.ams.service.system.ISysUserRoleService;
import org.example.ams.service.system.ISysUserService;
import org.example.ams.util.SystemUtils;
import org.example.common.constant.RedisConstant;
import org.example.security.util.LoginUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private ISysUserDao sysUserDao;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SystemUtils systemUtils;
    @Autowired
    private RedissonClient redissonClient;
    @Value("${default-password}")
    private String defaultPassword;
    @Value("${admin-usercode}")
    private Integer adminUserCode;

    @Override
    public Map<String,Object> queryUserByPage(Integer currentPage, Integer pageSize, String username) {
        Page<SysUser> page = new Page<SysUser>(currentPage,pageSize);
        Page<SysUser> ipage = null;
        ipage = sysUserDao.selectUserWithRoles(page, username);
        // 数据转化
        Map<Integer, String> userIdToNameMapper = systemUtils.getUserIdToNameMapper();
        List<SysUser> records = ipage.getRecords();
        for (SysUser record : records) {
            if (record.getCreateUserId() != null) {
                record.setCreateUsername(userIdToNameMapper.get(record.getCreateUserId()));
            }
        }
        Map<String,Object> res = new HashMap<>();
        res.put("total",ipage.getTotal());
        res.put("data",records);
        return res;
    }

    @Override
    public Integer addUser(SysUser sysUser) {
        // 如果用户名为admin，则添加错误
        if ("admin".equals(sysUser.getUsername())) {
            return 1;
        }
        String lockName = RedisConstant.LOCK_PRE + "system:adduser";
        RLock lock = redissonClient.getLock(lockName);
        try {
            boolean flag = lock.tryLock(RedisConstant.MAX_WAIT_LOCK_TIME,RedisConstant.LOCK_LEASE_TIME,RedisConstant.LOCK_LEASE_TIME_UNIT);
            if (flag) {
                // 设置用户编码，从数据库中查找目前编码最大值
                int max = Integer.parseInt(getMaxUserCode());
                int usercode = 0;
                if (max == 0) {
                    usercode = 100001;
                } else {
                    usercode = max + 1;
                    if (usercode == adminUserCode) {
                        usercode = usercode + 1;
                    }
                }
                sysUser.setUserCode(String.valueOf(usercode));
                // 设置默认密码
                sysUser.setPassword(passwordEncoder.encode(defaultPassword));
                // 设置账号状态为启用状态
                sysUser.setStatus(true);
                // 设置账号为有效账号（逻辑删除字段为true）
                sysUser.setIsValid(true);
                // 设置创建者id
                UserDetails userDetails = LoginUtils.currentLoginUser();
                SysUser loginUserInfo = sysUserDao.selectOne(new QueryWrapper<SysUser>().eq("username",userDetails.getUsername()));
                sysUser.setCreateUserId(loginUserInfo.getUserId());
                // 设置创建时间
                sysUser.setCreateTime(new Date());
                // 设置更新时间
                sysUser.setUpdateTime(new Date());
                // 设置为非超级管理员（超级管理员是系统默认用户，无法新建）
                sysUser.setIsAdmin(false);
                sysUserDao.insert(sysUser);
            } else {
                return 2;
            }
        } catch (Exception e) {
            log.error("获取锁异常============> {}",e.getMessage());
        } finally {
            lock.unlock();
        }
        return 0;
    }

    @Override
    public void update(SysUser user) {
        sysUserDao.updateById(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(Integer[] ids) {
        sysUserDao.deleteBatchIds(Arrays.asList(ids));
        // 删除用户拥有的角色
        if (ids != null && ids.length > 0) {
            for (Integer id : ids) {
                sysUserRoleService.deleteAll(id);
            }
        }
    }

    @Override
    public void updateStatus(Integer userId) {
        sysUserDao.updateStatus(userId);
    }

    @Override
    public List<SysUser> queryAll() {
        return sysUserDao.selectList(null);
    }


    /**
     * 获取当前最大用户编码
     * @return
     */
    private String getMaxUserCode() {
        return sysUserDao.selectMaxUserCode();
    }

    @Override
    public SysUser queryByUsername(String systemDefaultUserName) {
        return sysUserDao.selectOne(new QueryWrapper<SysUser>().eq("username",systemDefaultUserName));
    }
}
